package CustomClassFile.yueli;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import CustomClassFile.CronJob.DateUtil;
import CustomClassFile.CronJob.Pbzxx;
import weaver.conn.RecordSet;

public class KaoqinDk {
	public static final Log logger = LogFactory.getLog(KaoqinDk.class);
	
	//插入打卡信息
	/**
	 * 
	 * @param curruserid
	 * @param kqrq
	 * @param kqsj
	 * @param kqdd
	 * @param kqdjwd
	 * @param kqdkjd
	 * @param kqdkwd
	 * @param curraddress
	 * @param formmodeid
	 * @param modedatacreater
	 * @param modedatacreatertype
	 * @param modedatacreatedate
	 * @param modedatacreatetime
	 * @param kqlx
	 * @param pbsj
	 * @param sbxb
	 * @param kqdbh
	 * @param bcbh
	 * @param isflow
	 * @param dkcard
	 * @param dkcardstatus
	 * @param flowdataid
	 * @return
	 */
	public static boolean  insertDaKa(
			String curruserid,
			String kqrq,
			String kqsj,
			String kqdd,
			String kqdjwd,
			String kqdkjd,
			String kqdkwd,
			String curraddress,
			String formmodeid,
			String modedatacreater,
			String modedatacreatertype,
			String modedatacreatedate,
			String modedatacreatetime,
			String kqlx,
			String pbsj,
			String sbxb,
			String kqdbh,
			String bcbh,
			String isflow,
			String dkcard,
			String dkcardstatus,
			String flowdataid
			) {
		formmodeid="2";
		modedatacreater=curruserid;
		modedatacreatertype="0";
		modedatacreatedate=DateUtil.getCurrentDateTime("yyyy-MM-dd");
		modedatacreatetime=DateUtil.getCurrentDateTime("HH:mm:ss");
		
		//查询eid
		String sqleid="select lastname,outkey from hrmresource where id=?";
		String eid="";
		String name="";
		RecordSet rseid = new RecordSet();	
		rseid.executeQuery(sqleid, curruserid);
		
		if(rseid.next()) {
			eid=rseid.getString("outkey");
			name=rseid.getString("lastname");
		}
				
		RecordSet rs = new RecordSet();
		String sql="insert into uf_kqxx (kqry,kqrq,kqsj,kqdd,kqdjwd,kqdkjd,kqdkwd,kqrdkdd,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,kqlx,pbsj,sbxb,kqdbh,bcbh,isflow,dkcard,dkcardstatus,flowdataid,eid) "
				+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		boolean flag= rs.executeUpdate(sql, 
				 curruserid,
				 kqrq,
				 kqsj,
				 kqdd,
				 kqdjwd,
				 kqdkjd,
				 kqdkwd,
				 curraddress,
				 formmodeid,
				 modedatacreater,
				 modedatacreatertype,
				 modedatacreatedate,
				 modedatacreatetime,
				 kqlx,
				 pbsj,
				 sbxb,
				 kqdbh,
				 bcbh,
				 isflow,
				 dkcard,
				 dkcardstatus,
				 flowdataid,
				 eid);
		if (flag) {
			if("JiaBan".equals(bcbh)) {//如果是节假日加班
				if("card1".equals(dkcard)) {//如果是第一次打卡
					String sql1="update uf_zsws_jbdjb set card1=?  where sqr=? and jbrq=?";
					RecordSet rs1=new RecordSet();
					rs1.executeUpdate(sql1, kqsj,curruserid,kqrq);
					
				}
				if("card2".equals(dkcard)) {//如果是第二次次打卡
					String sqlfirst="select top 1* from uf_zsws_jbdjb where sqr=? and jbrq=? order by id desc ";
					RecordSet rsfirst=new RecordSet();
					rsfirst.executeQuery(sqlfirst,curruserid,kqrq);	
					if(rsfirst.next()) {//读取第一次打卡
						String card1=rsfirst.getString("card1");
						String hjsqxss=rsfirst.getString("hjsqxss");//申请小时数
						
						if (isNotEmpty(card1)) {
							BigDecimal hours=getTimeDifference(kqsj, card1);
							BigDecimal sqhours=new BigDecimal(hjsqxss);//申请小时数
							if (hours.compareTo(sqhours)>0) {//如果加班计算出来的小时数>申请加班小时数，则取小原则
								hours=sqhours;
							}
							BigDecimal days=hours.multiply(BigDecimal.valueOf(0.125)).setScale(4, BigDecimal.ROUND_DOWN);
							String sql2="update uf_zsws_jbdjb set card2=?,hjsjxss=?,hjsjts=?  where sqr=? and jbrq=?";
							RecordSet rs2=new RecordSet();
							rs2.executeUpdate(sql2, kqsj,hours,days,curruserid,kqrq);
							
							updateOrInsert(eid, name, days.toString());
							
						}else {
							String sql2="update uf_zsws_jbdjb set card2=?  where sqr=? and jbrq=?";
							RecordSet rs2=new RecordSet();
							rs2.executeUpdate(sql2, kqsj,curruserid,kqrq);	
						}
					
					}
					
							
				}
				if("card3".equals(dkcard)) {//如果是第三次打卡
					String sql3="update uf_zsws_jbdjb set card3=?  where sqr=? and jbrq=?";
					RecordSet rs3=new RecordSet();
					rs3.executeUpdate(sql3, kqsj,curruserid,kqrq);
				}
				if("card4".equals(dkcard)) {//如果是第四次打卡
					String sqlfirst="select top 1* from uf_zsws_jbdjb where sqr=? and jbrq=? order by id desc ";
					RecordSet rsfirst=new RecordSet();
					rsfirst.executeQuery(sqlfirst,curruserid,kqrq);	
					if(rsfirst.next()) {//读取第一次打卡
						String card3=rsfirst.getString("card3");
						String hjsqxss=rsfirst.getString("hjsqxss");//申请小时数
						String hjsjxss=rsfirst.getString("hjsjxss");//上午实际加班的小时数
						if (isNotEmpty(card3)) {
							BigDecimal hours=getTimeDifference(kqsj, card3);
							BigDecimal sqhours=new BigDecimal(hjsqxss);//申请小时数
							BigDecimal swsjhours=new BigDecimal(hjsjxss);//上午实际加班的小时数
							BigDecimal allhours=hours.add(swsjhours); //加上上午的加班数判断
							if (allhours.compareTo(sqhours)>0) {//如果上午加班+下午加班计算出来的小时数>申请加班小时数，则取小原则
								allhours=sqhours;
							}
							BigDecimal xwsjhours=allhours.subtract(swsjhours);//下午实际加班有效的小时数
							BigDecimal xwdays=xwsjhours.multiply(BigDecimal.valueOf(0.125)).setScale(4, BigDecimal.ROUND_DOWN);
							BigDecimal days=allhours.multiply(BigDecimal.valueOf(0.125)).setScale(4, BigDecimal.ROUND_DOWN);
						
							String sql4="update uf_zsws_jbdjb set card4=?,hjsjxss=?,hjsjts=?  where sqr=? and jbrq=?";
							RecordSet rs4=new RecordSet();
							rs4.executeUpdate(sql4, kqsj,allhours,days,curruserid,kqrq);
							
							updateOrInsert(eid, name, xwdays.toString());
						
							
						}else {
							String sql4="update uf_zsws_jbdjb set card4=?  where sqr=? and jbrq=?";
							RecordSet rs4=new RecordSet();
							rs4.executeUpdate(sql4, kqsj,curruserid,kqrq);	
						}
					
					}
				}
			}
		}
		return flag;
	}

	public static boolean updateOrInsert(String eid,String name,String days) {
		boolean flag=false;
		String sqlcheck="select * from uf_zswsHRaBal_buxiu where eid=?";
		RecordSet rssqlcheck=new RecordSet();
		rssqlcheck.executeQuery(sqlcheck,eid);
		if(rssqlcheck.next()) {//如果有记录
			String sqlbuxiudjb=" update   uf_zswsHRaBal_buxiu set expr1=isnull(CONVERT(decimal(15,4),expr1),0)+? where eid=?";
			RecordSet rssqlbuxiudjb=new RecordSet();
			flag=rssqlbuxiudjb.executeUpdate(sqlbuxiudjb, days,eid);
		}else {
			String insert="insert into uf_zswsHRaBal_buxiu(eid,name,baltype,expr1)values(?,?,?,?)";
			RecordSet rsinsert=new RecordSet();
			flag=rsinsert.executeUpdate(insert, eid,name,3,days.toString());
		}
		return flag;
	} 
	
	/***
	 * @comments 计算两个时间的时间差(加班小时数)
	 * @param strTime1
	 * @param strTime2
	 */
	public  static BigDecimal getTimeDifference(String strTime1,String strTime2) {
		BigDecimal hours=BigDecimal.ZERO;
		SimpleDateFormat df = new SimpleDateFormat("HH:mm");
		   try{
			   Date date1 = df.parse(strTime1);
			   Date date2=df.parse(strTime2);
			   BigDecimal diff=BigDecimal.valueOf(date1.getTime()-date2.getTime());       //获取时间差
			   BigDecimal unit=BigDecimal.valueOf(60*60*1000);//小时换算进制
			   
			   BigDecimal hourcalc= diff.divide(unit, 1, BigDecimal.ROUND_DOWN);//舍模式保留1位小数
			   int hour10=hourcalc.multiply(BigDecimal.TEN).intValue();//乘10转化为整数
			   if (hour10%10<5) {//如果不足半小时
				   hours=BigDecimal.valueOf(hour10/10).setScale(1, BigDecimal.ROUND_DOWN);
				   
			   }else {//超出半小时一律算0.5
				   hours=BigDecimal.valueOf((hour10/10)+0.5).setScale(1, BigDecimal.ROUND_DOWN);
				 
			   }
//			   if (hours.compareTo(BigDecimal.valueOf(4))>0){
//				   hours=BigDecimal.valueOf(4).setScale(1);
//			}
		   }catch(Exception e){
			   e.printStackTrace();
		   }
		   return hours;
	}
	
	/**
	   * 获取对应日期的排班信息
	 * @param id
	 * @param date
	 * @return
	 * 	查询归档日期在事件开始日期之前的数据（相同类型最后一条有效数据）
	 */
	public static Map<String ,Object> getDayPb(String id,String date){
		 Map<String ,Object> pbmap=new HashMap<>();
		String sql="select top 1* from uf_pbbdxx where  applicant =? and convert(date,changeDate,20) =? "
				+ "and convert(date,confirmdate,20)<=convert(date,datestart,20) order by id desc ";
		RecordSet rs = new RecordSet();
		boolean flag=rs.executeQuery(sql, id,date);
		
		if(flag&&rs.next()) {
			String type=rs.getString("type");
			String applicant=rs.getString("applicant");
			String card1=rs.getString("card1");
			String card2=rs.getString("card2");
			String card3=rs.getString("card3");
			String card4=rs.getString("card4");
			String cardtimes=rs.getString("cardtimes");
			String changeDate=rs.getString("changeDate");
			String changepbday=rs.getString("changepbday");
			String confirmdate=rs.getString("confirmdate");
			String dateend=rs.getString("dateend");
			String datestart=rs.getString("datestart");
			String endT1=rs.getString("endT1");
			String endT2=rs.getString("endT2");
			String endT3=rs.getString("endT3");
			String endT4=rs.getString("endT4");
			String endTime=rs.getString("endTime");
			String remarks=rs.getString("remarks");
			String requestId=rs.getString("requestId");
			String scan1=rs.getString("scan1");
			String scan2=rs.getString("scan2");
			String scan3=rs.getString("scan3");
			String scan4=rs.getString("scan4");
			String shenqindate=rs.getString("shenqindate");
			String shift=rs.getString("shift");
			String startTime=rs.getString("startTime");
			String title=rs.getString("title");
			String xhours=rs.getString("xhours");
			String xtype=rs.getString("xtype");
			switch (type) {
			case "0"://请假
				List<Map<String ,Object>> listmap0=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap0.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap0.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap0.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap0.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap0)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "1"://调休
				List<Map<String ,Object>> listmap1=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap1.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap1.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap1.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap1.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap1)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "2"://休息日加班
				List<Map<String ,Object>> listmap2=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap2.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap2.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap2.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap2.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap2)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "3"://外派
				List<Map<String ,Object>> listmap3=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap3.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap3.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap3.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap3.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap3)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "4"://出差
				List<Map<String ,Object>> listmap4=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap4.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap4.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap4.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap4.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap4)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "5"://培训
				List<Map<String ,Object>> listmap5=new ArrayList<>();
				if (isNotEmpty(card1)) {
					listmap5.add(getDkbc(id,date,card1, scan1, endT1, "card1", 0));
				}
				if (isNotEmpty(card2)) {
					listmap5.add(getDkbc(id,date,card2, scan2, endT2, "card2", 1));
				}
				if (isNotEmpty(card3)) {
					listmap5.add(getDkbc(id,date,card3, scan3, endT3, "card3", 0));
				}
				if (isNotEmpty(card4)) {
					listmap5.add(getDkbc(id,date,card4, scan4, endT4, "card4", 1));
				}	
				pbmap.put("jsontime", listmap5)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				break;
			case "6"://平日加班
				List<Map<String ,Object>> listmap6=new ArrayList<>();//平日加班特殊处理，追加在当前排班组后面
			
				if (isNotEmpty(card1)) {
					listmap6.add(getDkbc(id,date,card1, scan1, endT1, "card5", 0));
				}
				if (isNotEmpty(card2)) {
					listmap6.add(getDkbc(id,date,card2, scan2, endT2, "card6", 1));
				}
				if (isNotEmpty(card3)) {
					listmap6.add(getDkbc(id,date,card3, scan3, endT3, "card7", 0));
				}
				if (isNotEmpty(card4)) {
					listmap6.add(getDkbc(id,date,card4, scan4, endT4, "card8", 1));
				}	
				pbmap.put("jsontime", listmap6)	;
				pbmap.put("shiftType", shift)	;
				pbmap.put("title", title)	;
				Pbzxx pbz=getPbzxx(id, date);
				if(pbz==null) {//如果当天没有排班
					pbmap.put("jsontime", new ArrayList<>())	;
					pbmap.put("shiftType", "R")	;
					pbmap.put("title", "休息")	;
				}else {
					List<Map<String ,Object>> listmap=new ArrayList<>();
					if(isNotEmpty(pbz.getCard1())) {
						listmap.add(getDkbc(id,date,pbz.getCard1(), pbz.getScan1(), pbz.getEndT1(), "card1", 0));
					}
					if(isNotEmpty(pbz.getCard2())) {
						listmap.add(getDkbc(id,date,pbz.getCard2(), pbz.getScan2(), pbz.getEndT2(), "card2", 1));
					}
					if(isNotEmpty(pbz.getCard3())) {
						listmap.add(getDkbc(id,date,pbz.getCard3(), pbz.getScan3(), pbz.getEndT3(), "card3", 0));
					}
					if(isNotEmpty(pbz.getCard4())) {
						listmap.add(getDkbc(id,date,pbz.getCard4(), pbz.getScan4(), pbz.getEndT4(), "card4", 1));
					}
					//listmap.addAll(listmap6);//追加加班排班，暂时不处理，以后再说
					pbmap.put("jsontime", listmap)	;
					pbmap.put("shiftType", pbz.getShift())	;
					pbmap.put("title",pbz.getTitle())	;
				}
				break;

			default:
				break;
			}
		}else {//查询正常排班
			Pbzxx pbz=getPbzxx(id, date);
			if(pbz==null) {//如果当天没有排班
				pbmap.put("jsontime", new ArrayList<>())	;
				pbmap.put("shiftType", "R")	;
				pbmap.put("title", "休息")	;
			}else {
				List<Map<String ,Object>> listmap=new ArrayList<>();
				if(!StringUtils.isBlank(pbz.getCard1())) {
					listmap.add(getDkbc(id,date,pbz.getCard1(), pbz.getScan1(), pbz.getEndT1(), "card1", 0));
				}
				if(!StringUtils.isBlank(pbz.getCard2())) {
					listmap.add(getDkbc(id,date,pbz.getCard2(), pbz.getScan2(), pbz.getEndT2(), "card2", 1));
				}
				if(!StringUtils.isBlank(pbz.getCard3())) {
					listmap.add(getDkbc(id,date,pbz.getCard3(), pbz.getScan3(), pbz.getEndT3(), "card3", 0));
				}
				if(!StringUtils.isBlank(pbz.getCard4())) {
					listmap.add(getDkbc(id,date,pbz.getCard4(), pbz.getScan4(), pbz.getEndT4(), "card4", 1));
				}
				pbmap.put("jsontime", listmap)	;
				pbmap.put("shiftType", pbz.getShift())	;
				pbmap.put("title",pbz.getTitle())	;
			}
		}
		return pbmap;
		
	}
	/**
	 *     获取打卡班次
	 * @param card
	 * @param scan
	 * @param endT
	 * @param cardname//班次name
	 * @param sbxb 0上班1下班
	 * @return
	 */
	private static Map<String,Object> getDkbc(String id,String date,String card,String scan,String endT,String cardname,int sbxb){
		Map<String,Object> map=new HashMap<>();
		map.put("time", mySubStr(card));//去掉秒
		map.put("start", mySubStr(scan));
		map.put("end", mySubStr(endT));
		map.put("content","("+mySubStr(scan)+"-"+mySubStr(endT)+")");
		map.put("card", cardname);
		map.put("sbxb", sbxb);
		
		boolean iswaiqing=iswqsq(id, date, cardname);
		map.put("iswaiqing", iswaiqing);
		return map;
	}
	
	// 查询排班组信息
	public static Pbzxx getPbzxx(String id, String date) {
		String sql = "select t.* from hrmresource  h inner join uf_rypbxx z on h.outkey=z.eid and h.id=? and CONVERT(date,z.term,20)=? inner join uf_pbzxx t "
				+ "on z.shift=t.shift and (t.isdisabled='1' or t.isdisabled is null)";
		RecordSet rs = new RecordSet();
		rs.executeQuery(sql, id, date);
		Pbzxx pbz = null;
		while (rs.next()) {
			pbz = new Pbzxx();
			pbz.setShift(rs.getString("shift"));
			pbz.setTitle(rs.getString("title"));
			pbz.setCard1(rs.getString("card1"));
			pbz.setCard2(rs.getString("card2"));
			pbz.setCard3(rs.getString("card3"));
			pbz.setCard4(rs.getString("card4"));
			pbz.setScan1(rs.getString("scan1"));
			pbz.setScan2(rs.getString("scan2"));
			pbz.setScan3(rs.getString("scan3"));
			pbz.setScan4(rs.getString("scan4"));
			pbz.setEndT1(rs.getString("endT1"));
			pbz.setEndT2(rs.getString("endT2"));
			pbz.setEndT3(rs.getString("endT3"));
			pbz.setEndT4(rs.getString("endT4"));
			pbz.setXhours(rs.getString("Xhours"));
			pbz.setCardTimes(rs.getString("CardTimes"));
		}
		return pbz;
	}
	//判断当次打卡有没有申请外勤
	private static boolean iswqsq(String id,String date,String cardname) {
		String sql = "select * from uf_wqsq where sqrid=? and sqrq=? and sqcard=?";
		RecordSet rs = new RecordSet();
		boolean flag=rs.executeQuery(sql, id, date,cardname);
		if(flag&&rs.next()) {
			return true;
		}
		return false;
	}
	
	///判断打卡card是否有效
	private static boolean isNotEmpty (String card) {
		if(!StringUtils.isEmpty(StringUtils.trim(card))&&!"NULL".equalsIgnoreCase(StringUtils.trim(card))) {
			return true;
		}
		return false;
	}
		
	///将时间字符串 HH:mm:ss截取为HH:mm
	private static String mySubStr(String card) {
		if(card!=null&&StringUtils.trim(card).length()>5) {
			card=StringUtils.trim(card).substring(0, 5);
		}
		return card;
	}
	
}
